package com.zxy.springboot_vue.controller;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zxy.domain.FileResult;
import com.zxy.service.FileService;
import com.zxy.springboot_vue.common.SendMsgUtil;
import com.zxy.springboot_vue.config.AjaxResult;
import com.zxy.springboot_vue.config.JwtTokenUtil;
import com.zxy.springboot_vue.entity.City;
import com.zxy.springboot_vue.entity.User;
import com.zxy.springboot_vue.service.ICityService;
import com.zxy.springboot_vue.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lenovo
 * @since 2021-10-19
 */
@RestController
@RequestMapping("/user")
@CrossOrigin    //解决跨域问题 不推荐使用,使用MvcConfig的方式
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private FileService fileService;
    @Autowired
    private ICityService cityService;
    /*@Autowired
    private KafkaTemplate<String, String> kafkaTemplate;*/

    @RequestMapping("list")
    public AjaxResult list(User user, @RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "3") Integer pageSize) {
        QueryWrapper<User> wrapper = null;
        PageHelper.startPage(pageNum, pageSize);
        if (user.getName() != null) {
            wrapper = new QueryWrapper();
            wrapper.like("name", user.getName());
        }
        List<User> list = userService.list(wrapper);
        PageInfo<User> info = new PageInfo<>(list);
        return AjaxResult.ok(info);
    }

    @PostMapping("addUser")
    public AjaxResult addUser(@RequestBody User user) {
        System.err.println(user);
        if (user.getDistrict() != null) {
            City province = cityService.getById(user.getProvince());
            City city = cityService.getById(user.getCity());
            City district = cityService.getById(user.getDistrict());

            user.setAddress(province.getCityname() + city.getCityname() + district.getCityname());
        }
        //获取用户的密码,加密之后再存入实体类,保存
        String password = user.getPassword();
        String secPassword = SecureUtil.md5(password);
        user.setPassword(secPassword);
        boolean b = userService.saveOrUpdate(user);
        return AjaxResult.ok(b);

    }

    @PostMapping("delAll")
    public AjaxResult delAll(@RequestBody User user) {
        boolean b = userService.removeByIds(user.getIds());
        return AjaxResult.ok(b);
    }

    @RequestMapping("upload")
    public FileResult upload(MultipartFile[] file) {
        System.err.println("--------upload---------------" + file);
        List<FileResult> upload = fileService.upload(file);
        return upload.get(0);
    }

    @RequestMapping("getOne")
    public AjaxResult getOne(Integer id) {
        User user = userService.getById(id);
        return AjaxResult.ok(user);
    }

    @RequestMapping("login")
    //@Idempotent(key = "#user.username",expireTime =10,info = "请勿重复提交")
    public Object login(User user) {
        String newPassword = SecureUtil.md5(user.getPassword());
        user.setPassword(newPassword);

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        wrapper.eq("password", user.getPassword());
        User one = userService.getOne(wrapper);
        System.err.println(one);
        if (one == null) {
            //return AjaxResult.err(400, "登陆失败");
            return false;
        }
        //从数据库对比用户名和密码是否正确,如果能查询出来,说明正确

        //使用token进行登录
        JwtTokenUtil jwt = new JwtTokenUtil();
        String token = jwt.generateToken(one);
        System.err.println(token + "**********");

        return token;


        //通过kafka发送消息
            /*String s = "";
            for (User user1 : list) {
                s = JSONObject.toJSON(user1).toString();
            }
            System.err.println(s);
            log.info("通过kafka发送消息---------------------");
            kafkaTemplate.send("1904a",s);*/

    }


    @RequestMapping("validate")
    @ResponseBody
    public Object validate(){
        JwtTokenUtil<User> tokenUtil = new JwtTokenUtil<>();

        boolean b = tokenUtil.validateToken("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJsaXNpIiwiY3JlYXRlZCI6MTYxODIwOTEwNzM2OCwiZXhwIjoxNjE4ODEzOTA3fQ.lMmtAfMRilQBbHcGmj0YVtV4sEPCuKRk-1u98tkXTW4f1WKYDFnuyaA46H7sunTyZkbexq9SSegdIcAbPQqtvg");
        System.out.println("token有效?"+b);
        String username = tokenUtil.getUserNameFromToken("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJsaXNpIiwiY3JlYXRlZCI6MTYxODIwOTEwNzM2OCwiZXhwIjoxNjE4ODEzOTA3fQ.lMmtAfMRilQBbHcGmj0YVtV4sEPCuKRk-1u98tkXTW4f1WKYDFnuyaA46H7sunTyZkbexq9SSegdIcAbPQqtvg");
        System.out.println("username="+username);
        String newToken = tokenUtil.refreshHeadToken("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJsaXNpIiwiY3JlYXRlZCI6MTYxODIwOTEwNzM2OCwiZXhwIjoxNjE4ODEzOTA3fQ.lMmtAfMRilQBbHcGmj0YVtV4sEPCuKRk-1u98tkXTW4f1WKYDFnuyaA46H7sunTyZkbexq9SSegdIcAbPQqtvg");
        System.out.println("新的token为:"+newToken);
        return b;
    }

}
